package models

import (
	"errors"
	"time"

	"xorm.io/xorm"
)

type Business struct {
	Id            int64
	Name          string
	ContactsName  string
	ContactsPhone string
	Address       string
	WorkTime      string
	Preferential  string
	Img           []string
	Sort          int64
	UserId        int64
	DealerId      int64
	DeleteAt      time.Time `xorm:"deleted"`
	//Lng           float64
	//Lat           float64
	//Province      string
	//City          string
	//District      string
}

func (m *Business) Save(engine *xorm.Engine) error {
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	if m.Id > 0 {
		_, err := session.ID(m.Id).MustCols("user_id", "dealer_id").Update(m)

		if err != nil {
			session.Rollback()
			return err
		}
	} else {
		_, err := session.Insert(m)
		if err != nil {
			session.Rollback()
			return err
		}
	}
	if m.UserId > 0 {
		member := &Member{Id: m.UserId}
		get, err := engine.Get(member)
		if err != nil {
			session.Rollback()
			return err
		}
		if !get {
			session.Rollback()
			return errors.New("获取商家账号失败")
		}
		if len(member.LsUser) == 0 || len(member.LsCard) == 0 {
			session.Rollback()
			return errors.New("请商家先完成实名认证和绑卡")
		}
		// if member.BusinessId == 0 {
		member.BusinessId = m.Id
		_, err = session.ID(member.Id).Update(member)
		if err != nil {
			session.Rollback()
			return err
		}
		// }

		exist, err := engine.Exist(&BusinessMember{MemberId: member.Id, BusinessId: m.Id})
		if err != nil {
			session.Rollback()
			return err
		}
		if !exist {
			bm := &BusinessMember{
				Id:             0,
				MemberId:       member.Id,
				MemberName:     member.Name,
				BusinessId:     m.Id,
				BusinessName:   m.Name,
				InviteId:       0,
				IsIndependence: 2,
				MemberPhone:    member.Phone,
			}
			_, err = session.Insert(bm)
			if err != nil {
				session.Rollback()
				return err
			}
		}

	}
	if m.DealerId > 0 {
		member := &Member{Id: m.DealerId}
		get, err := engine.Get(member)
		if err != nil {
			session.Rollback()
			return err
		}
		if !get {
			session.Rollback()
			return errors.New("获取经销商账号失败")
		}
		if len(member.LsUser) == 0 || len(member.LsCard) == 0 {
			session.Rollback()
			return errors.New("请经销商先完成实名认证和绑卡")
		}

		exist, err := engine.Exist(&BusinessMember{MemberId: member.Id, BusinessId: m.Id})
		if err != nil {
			session.Rollback()
			return err
		}
		if !exist {
			bm := &BusinessMember{
				Id:             0,
				MemberId:       member.Id,
				MemberName:     member.Name,
				BusinessId:     m.Id,
				BusinessName:   m.Name,
				InviteId:       0,
				IsIndependence: 2,
				MemberPhone:    member.Phone,
			}
			_, err = session.Insert(bm)
			if err != nil {
				session.Rollback()
				return err
			}
		}

	}

	session.Commit()

	return nil
}
